import * as OSSApi from "@/api/oss";
import * as KKApi from "@/api/index";

const KKOssTokenKey = "KKOssToken";
const KKTokenKey = "KKToken";
const KKUserInfoKey = "KKUserInfo";
const KKUserLoginPhoneKey = "KKUserLoginPhone";
const KKMyQrCodeKey = "KKMyQrCode";

//登录APP初始化OSSToken
export const launchAppInitOssToken = async () => {
  const data = (await OSSApi.fetchOSSConfig().catch(() => {})) as any;
  if (data && data.data) {
    uni.setStorageSync(KKOssTokenKey, data.data);
    const expiration = new Date(data.data.expiration).getTime() - 2 * 60 * 1000;
    const expire = expiration - new Date().getTime();
    setTimeout(() => {
      launchAppInitOssToken();
    }, expire);
  }
};

// 保存OSS token
export const saveOssToken = (data: any) => {
  uni.setStorageSync(KKOssTokenKey, data || {});
};

export const getOssToken = () => {
  const ossToken = uni.getStorageSync(KKOssTokenKey) || {};
  if (ossToken && ossToken.accessKeyId) {
    const expiration = new Date(ossToken.expiration).getTime() - 2 * 60 * 1000;
    if (new Date().getTime() > expiration) {
      fetchOSSConfig();
    }

    return ossToken;
  } else {
    fetchOSSConfig();
  }
  return ossToken;
};

const fetchOSSConfig = async () => {
  const data = (await OSSApi.fetchOSSConfig().catch(
    () => {}
  )) as KKApi.KKResponseData;
  if (data && data.data) {
    uni.setStorageSync(KKOssTokenKey, data.data);
  }
};

// 保存token
export const saveKKToken = (token: string) => {
  uni.setStorageSync(KKTokenKey, token || "");
};

// 获取token
export const getKKToken = () => {
  return uni.getStorageSync(KKTokenKey) || "";
};

// 保存用户信息
export const saveUserInfo = (data: any) => {
  uni.setStorageSync(KKUserInfoKey, data || {});
};

// 获取用户信息
export const getUserInfo = () => {
  return uni.getStorageSync(KKUserInfoKey) || {};
};

// 保存用户登录手机号
export const saveUserLoginPhone = (data: any) => {
  uni.setStorageSync(KKUserLoginPhoneKey, data || {});
};

// 获取用户登录手机号
export const getUserLoginPhone = () => {
  return uni.getStorageSync(KKUserLoginPhoneKey) || {};
};

// 保存公众号二维码
export const saveQrCodeUrl = (url: string) => {
  uni.setStorageSync(KKMyQrCodeKey, { url: url, time: new Date().getTime() });
};

// 获取公众号二维码
export const getQrCodeUrl = () => {
  const qrCode = uni.getStorageSync(KKMyQrCodeKey) || { url: "", time: "" };
  return qrCode.url || "";
};

// 公众号码是否过期
export const getQrCodeUrlIsExpire = () => {
  const qrCode = uni.getStorageSync(KKMyQrCodeKey) || { url: "", time: "" };
  const time = Number(qrCode.time);
  const currentTime = new Date().getTime();
  if (time > 0 && currentTime - time > 1000 * 60 * 60 * 24 * 20) {
    //有效期 30天 默认10天请求一次
    return true;
  }
  return false;
};
